﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DiyBook.Models;

namespace DiyBook.Controllers
{
    public class ManagerController : Controller
    {
        //
        // GET: /Manager/
        
        BooksDB db = new BooksDB();
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            var managers = from m in db.Manager
                           select m;
            return View(managers.ToList());
        }
        [Authorize(Roles = "Admin")]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Manager newManager)
        {
            if (ModelState.IsValid)
            {
                db.Manager.Add(newManager);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
                return View(newManager);
        }
        [Authorize(Roles = "Admin")]
        public ActionResult Details(int id)
        {
            Manager manager = db.Manager.Find(id);
            if (manager == null)
                return RedirectToAction("Index");
            return View("Details", manager);
        }
        [Authorize(Roles = "Admin")]
        public ActionResult Edit(int id)
        {
            Manager manager = db.Manager.Find(id);
            if (manager == null)
                return RedirectToAction("Index");

            return View(manager);
        }

        [HttpPost]
        public ActionResult Edit(Manager model)
        {
            try
            {
                var manager = db.Manager.Find(model.managerID);
                UpdateModel(manager);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = model.managerID});
            }
            catch (Exception)
            {
                ModelState.AddModelError("","修改失败，请查看详细错误信息");
            }

            return View(model);
        }
        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int id)
        {
            Manager manager = db.Manager.Find(id);
            if (manager == null)
                return RedirectToAction("Index");
            return View(manager);
        }

        [HttpPost]
        public RedirectToRouteResult Delete(int id,FormCollection collection)
        {
            var manager =db.Manager.Find(id);
            db.Manager.Remove(manager);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
